<template>
  <div class="personal-center">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <i class="iconfont icon-book"></i>
        <span>考研真题训练系统</span>
      </div>
      <div class="user-info">
        <span class="welcome">欢迎回来，{{ userStore.username }}</span>
        <el-avatar :size="40" :src="userInfo.avatar"></el-avatar>
      </div>
    </header>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 侧边导航 -->
      <div class="sidebar">
        <div class="user-card">
          <el-avatar :size="80" :src="userInfo.avatar"></el-avatar>
          <div class="user-details">
            <h3>{{ userStore.username }}</h3>
            <p>VIP {{ userInfo.vipLevel }} 会员</p>
            <p>积分: {{ userInfo.points }}</p>
          </div>
        </div>

        <el-menu
          default-active="5"
          class="side-menu"
        >
          <el-menu-item index="1" >
    <router-link to="/personal-center/info" class="menu-link">
      <i class="iconfont icon-user"></i>
      <span>个人信息</span>
    </router-link>
  </el-menu-item>
  <el-menu-item index="2">
    <router-link to="/personal-center/edit" class="menu-link">
      <i class="iconfont icon-edit"></i>
      <span>修改资料</span>
    </router-link>
  </el-menu-item>
          <el-menu-item index="3">
    <router-link to="/personal-center/feedback" class="menu-link">
      <i class="iconfont icon-message"></i>
      <span>消息反馈</span>
    </router-link>
  </el-menu-item>
           <el-menu-item index="4" >
    <router-link to="/personal-center/notifications" class="menu-link">
      <i class="iconfont icon-notification"></i>
      <span>通知设置</span>
    </router-link>
  </el-menu-item>
          <el-menu-item index="5" class="active">
    <router-link to="/personal-center/cancel-account" class="menu-link">
      <i class="iconfont icon-logout"></i>
      <span>注销账户</span>
    </router-link>
  </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区 -->
      <div class="content">
        <!-- 注销账户 -->
        <div class="cancel-section">
          <h2 class="section-title">注销账户</h2>
          <div class="warning-box">
            <el-alert
              title="警告"
              type="warning"
              description="注销账户是不可恢复的操作，您的所有数据将被永久删除，包括学习记录、收藏题目和个人信息等。请谨慎操作！"
              show-icon
              :closable="false"
            >
            </el-alert>
          </div>
          
          <div class="cancel-form">
            <el-form :model="cancelForm" label-width="120px">
              <el-form-item label="注销原因">
                <el-select v-model="cancelForm.reason" placeholder="请选择注销原因">
                  <el-option label="不再使用该平台" value="1"></el-option>
                  <el-option label="找到了更好的平台" value="2"></el-option>
                  <el-option label="隐私担忧" value="3"></el-option>
                  <el-option label="其他原因" value="4"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="详细说明">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="cancelForm.description"
                  placeholder="请详细说明您的注销原因"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="cancelForm.confirm">
                  我理解并确认：注销账户后所有数据将无法恢复
                </el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button type="danger" :disabled="!cancelForm.confirm" @click="confirmCancel">
                  确认注销账户
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '@/store/user'
import { ref, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'AccountCancel',
  setup() {
    const userStore = useUserStore()
    
    onMounted(() => {
      userStore.initialize()
    })
    
    return {
      userStore
    }
  },
  data() {
    return {
      userInfo: {
        username: '考研学子',
        email: 'kaoyan@example.com',
        phone: '13800138000',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        vipLevel: 3,
        points: 1280,
        vipExpiry: '2024-12-31',
        studyDays: 86,
        completed: 1240,
        correctRate: 78
      },
      cancelForm: {
        reason: '',
        description: '',
        confirm: false
      }
    };
  },
  methods: {
    goToPage(pageName) {
      window.location.href = `./${pageName}`;
    },
    async confirmCancel() {
      // 检查必填项
      if (!this.cancelForm.reason) {
        this.$message.warning('请选择注销原因');
        return;
      }
      
      this.$confirm('确定要注销账户吗？此操作不可撤销，所有数据将被永久删除！', '警告', {
        confirmButtonText: '确认注销',
        cancelButtonText: '取消',
        type: 'error',
        center: true
      }).then(async () => {
        try {
          const userId = this.userStore.userId;
          
          // 调用后端删除接口 - 使用正确的路径和方法
          const response = await axios.delete('/userpro/delete', {
            params: {
              userId: userId
            }
          });
          
          // 检查响应
          if (response.status === 200 && response.data === "用户删除成功") {
            this.$message({
              type: 'success',
              message: '账户已注销，感谢您使用考研真题训练系统，3秒后自动跳转到登录页面'
            });
            
            // 清除用户状态和所有本地数据
            if (this.userStore.logout) {
              this.userStore.logout();
            }
            
            // 清除所有本地存储数据
            localStorage.clear();
            sessionStorage.clear();
            
            // 清除cookies (如果有的话)
            document.cookie.split(";").forEach(function(c) { 
              document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
            });
            
            // 3秒后跳转到登录页面
            let countdown = 3;
            const countdownInterval = setInterval(() => {
              countdown--;
              if (countdown > 0) {
                this.$message({
                  type: 'success',
                  message: `账户已注销，${countdown}秒后自动跳转到登录页面`
                });
              } else {
                clearInterval(countdownInterval);
                // 强制跳转到登录页面
                this.$router.push('/login').catch(() => {
                  // 如果路由跳转失败，直接刷新页面到登录页
                  window.location.href = '/login';
                });
              }
            }, 1000);
          } else {
            this.$message.error('账户注销失败: ' + (response.data || '未知错误'));
          }
        } catch (error) {
          console.error('注销账户失败:', error);
          
          let errorMessage = '账户注销失败';
          if (error.response) {
            if (error.response.status === 404) {
              errorMessage += ': 用户不存在';
            } else if (error.response.status === 405) {
              errorMessage += ': 请求方法不支持';
            } else {
              errorMessage += `: ${error.response.data || error.response.status}`;
            }
          } else if (error.request) {
            errorMessage += ': 无法连接到服务器';
          } else {
            errorMessage += `: ${error.message}`;
          }
          
          this.$message.error(errorMessage);
          
          // 如果API调用失败，提供一个模拟注销的选项
          this.$confirm('无法连接到服务器，是否模拟注销账户（仅清除本地数据）？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 清除本地数据
            localStorage.clear();
            sessionStorage.clear();
            
            this.$message({
              type: 'success',
              message: '本地数据已清除，即将跳转到登录页面'
            });
            
            // 立即跳转到登录页
            setTimeout(() => {
              this.$router.push('/login').catch(() => {
                // 如果路由跳转失败，直接刷新页面到登录页
                window.location.href = '/login';
              });
            }, 1500);
          }).catch(() => {
            // 用户取消了模拟注销
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消注销'
        });
      });
    }
  }
};
</script>

<style scoped>
.personal-center {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background: linear-gradient(135deg, #1e5799 0%,#207cca 100%);
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
}

.logo .iconfont {
  font-size: 28px;
  margin-right: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.welcome {
  margin-right: 15px;
  font-size: 14px;
}

.main-container {
  display: flex;
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

.sidebar {
  width: 260px;
  margin-right: 20px;
}

.user-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-details h3 {
  margin: 15px 0 5px;
  font-size: 18px;
}

.user-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.side-menu {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.side-menu .iconfont {
  margin-right: 10px;
  font-size: 18px;
}

.side-menu .el-menu-item {
  cursor: pointer;
}

.side-menu .el-menu-item.active {
  background-color: #ecf5ff;
  color: #409EFF;
}

.content {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  color: #303133;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.cancel-form {
  max-width: 700px;
  margin-top: 30px;
}

.warning-box {
  margin-bottom: 30px;
}

.el-alert {
  border-radius: 8px;
}
</style>